<template>
  <div class="dashboard-content">
    <!-- 中间内容区域 -->
    <main class="main-content">
      <!-- 左侧区域 - 占主体宽度55% -->
      <div class="left-section">
        <!-- 数据统计区域 - 占左侧高度35% -->
        <section class="stats-section">
          <div class="stats-card">
            <h3>数据统计</h3>
            <div class="stats-grid">
              <div class="stats-item">
                <span>今天订单数</span>
                <span class="value">5</span>
              </div>
              <div class="stats-item">
                <span>今天收入</span>
                <span class="value">￥120.00</span>
              </div>
              <div class="stats-item">
                <span>昨天订单数</span>
                <span class="value">7</span>
              </div>
              <div class="stats-item">
                <span>昨天收入</span>
                <span class="value">￥160.00</span>
              </div>
              <div class="stats-item">
                <span>总用户数</span>
                <span class="value">2,310</span>
              </div>
              <div class="stats-item">
                <span>总课程数</span>
                <span class="value">17</span>
              </div>
              <div class="stats-item">
                <span>总订单数</span>
                <span class="value">31</span>
              </div>
              <div class="stats-item">
                <span>总收入</span>
                <span class="value">￥1210.00</span>
              </div>
            </div>
          </div>
        </section>

        <!-- 课程类型统计区域 - 占左侧高度65% -->
        <section class="course-type-section">
          <div class="section-header">
            <h3>课程类型统计</h3>
            <div class="chart-type">
              <el-radio-group v-model="courseTypeChartType" @change="renderCourseTypeChart">
                <el-radio :value="'pie'">饼图</el-radio>
                <el-radio :value="'bar'">柱状图</el-radio>
              </el-radio-group>
            </div>
          </div>
          <div id="courseTypeChart" class="chart-container"></div>
        </section>
      </div>

      <!-- 右侧区域 - 占主体宽度45% -->
      <div class="right-section">
        <section class="course-watch-section">
          <div class="section-header">
            <h3>课程观看次数</h3>
            <div class="chart-filter">
              <el-select v-model="watchRange" placeholder="选择时间范围">
                <el-option label="今日" value="today"></el-option>
                <el-option label="本周" value="week"></el-option>
                <el-option label="本月" value="month"></el-option>
                <el-option label="全年" value="year"></el-option>
              </el-select>
            </div>
          </div>
          <div id="courseWatchChart" class="chart-container"></div>
        </section>
      </div>
    </main>
  </div>
</template>

<script>
// 脚本部分保持不变
import { ref, onMounted, onUnmounted, nextTick, watchEffect } from 'vue';
import { ElRadioGroup, ElRadio, ElSelect, ElOption } from 'element-plus';
import * as echarts from 'echarts';
import { getCourseStatistics, getCourseWatchCount } from '@/api/course.js';

export default {
  components: {
    ElRadioGroup,
    ElRadio,
    ElSelect,
    ElOption
  },
  setup() {
    const courseTypeChartType = ref('pie');
    const watchRange = ref('month');

    // ECharts 实例
    let courseTypeChart = null;
    let courseWatchChart = null;

    // 获取课程类型统计数据并渲染图表
    const fetchCourseTypeData = async () => {
      try {
        const res = await getCourseStatistics({
          page: 1,
          pageSize: 10,
        });
        if (res.code === 1) {
          const categories = res.data.items.map((item) => item.category);
          const data = res.data.items.map((item) => item.totalCourses);
          renderCourseTypeChart(courseTypeChartType.value, categories, data);
        } else {
          console.error('获取课程类型统计数据失败：', res.message);
        }
      } catch (error) {
        console.error('请求课程类型统计数据出错：', error);
      }
    };

    // 渲染课程类型图表
    const renderCourseTypeChart = (type, categories, data) => {
      setTimeout(() => {
        if (!courseTypeChart) {
          courseTypeChart = echarts.init(document.getElementById('courseTypeChart'));
        }

        const option = {
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b}: {c} ({d}%)'
          },
          legend: {
            type: 'scroll',
            orient: 'vertical',
            right: 10,
            top: 20,
            bottom: 20,
            data: categories
          },
          series: [
            {
              name: '课程数量',
              type: type,
              radius: type === 'pie' ? '55%' : '',
              center: ['40%', '50%'],
              data: data.map((item, index) => ({
                value: item,
                name: categories[index]
              })),
              emphasis: {
                itemStyle: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        };

        courseTypeChart.setOption(option);
        courseTypeChart.resize();
      }, 0);
    };

    // 获取课程观看次数数据并渲染图表
    const fetchCourseWatchData = async () => {
      try {
        const res = await getCourseWatchCount({
          page: 1,
          pageSize: 10,
          range: watchRange.value
        });
        if (res.code === 1) {
          const chapters = res.data.items.map((item) => item.chapter);
          const views = res.data.items.map((item) => item.views);
          renderCourseWatchChart(chapters, views);
        } else {
          console.error('获取课程观看次数失败：', res.message);
        }
      } catch (error) {
        console.error('请求课程观看次数出错：', error);
      }
    };

    // 渲染课程观看次数柱状图（横向）
    const renderCourseWatchChart = (chapters, views) => {
      setTimeout(() => {
        if (!courseWatchChart) {
          courseWatchChart = echarts.init(document.getElementById('courseWatchChart'));
        }

        const option = {
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              type: 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          xAxis: {
            type: 'value',
            boundaryGap: [0, 0.01]
          },
          yAxis: {
            type: 'category',
            data: chapters
          },
          series: [
            {
              name: '观看次数',
              type: 'bar',
              data: views,
              itemStyle: {
                color: '#5793f3'
              },
              label: {
                show: true,
                position: 'right',
                formatter: '{c}'
              }
            }
          ]
        };

        courseWatchChart.setOption(option);
        courseWatchChart.resize();
      }, 0);
    };

    // 监听窗口变化，自适应图表
    const resizeChart = () => {
      if (courseTypeChart) courseTypeChart.resize();
      if (courseWatchChart) courseWatchChart.resize();
    };

    // 监听范围变化，重新获取数据
    const onWatchRangeChange = () => {
      fetchCourseWatchData();
    };

    // 组件更新时重新计算图表尺寸
    const handleComponentUpdate = () => {
      if (courseTypeChart) courseTypeChart.resize();
      if (courseWatchChart) courseWatchChart.resize();
    };

    onMounted(() => {
      fetchCourseTypeData();
      fetchCourseWatchData();
      window.addEventListener('resize', resizeChart);
      watchEffect(handleComponentUpdate);
    });

    onUnmounted(() => {
      window.removeEventListener('resize', resizeChart);
      watchEffect(() => {});
      if (courseTypeChart) courseTypeChart.dispose();
      if (courseWatchChart) courseWatchChart.dispose();
    });

    return {
      courseTypeChartType,
      watchRange,
      renderCourseTypeChart,
      onWatchRangeChange
    };
  }
};
</script>

<style scoped>
/* 优化后的布局样式 - 明确盒模型和尺寸计算 */
* {
  box-sizing: border-box; /* 确保内边距和边框不影响尺寸计算 */
}

.dashboard-content {
  display: flex;
  padding: 20px;
  gap: 20px;
  height: calc(100vh - 60px); /* 匹配顶部标题栏高度 */
  width: 100%;
}

.main-content {
  flex: 1;
  display: flex;
  gap: 20px;
  width: 100%;
}

.left-section {
  flex: 0 0 55%; /* 左侧占主体宽度55% */
  display: flex;
  flex-direction: column;
  gap: 20px;
  height: 100%;
}

.stats-section {
  flex: 0 0 35%; /* 数据统计占左侧高度35% */
  min-height: 200px; /* 防止高度过小 */
}

.stats-card {
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  height: 100%;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 15px;
  height: calc(100% - 40px);
  align-content: center;
}

.stats-item {
  text-align: center;
  padding: 10px;
  border-radius: 4px;
  background-color: #f8f9fa;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.stats-item span:first-child {
  font-size: 14px;
  color: #6c757d;
  margin-bottom: 5px;
}

.stats-item .value {
  font-size: 18px;
  font-weight: bold;
  color: #343a40;
}

.course-type-section {
  flex: 0 0 62.7%; /* 课程类型统计占左侧高度65% */
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.chart-container {
  flex: 1;
  width: 100%;
  min-height: 300px;
}

.right-section {
  flex: 0 0 45%; /* 右侧占主体宽度45% */
  display: flex;
  flex-direction: column;
  gap: 20px;
  height: 100%;
}

.course-watch-section {
  flex: 1; /* 课程观看次数占右侧全部高度 */
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: column;
}

.chart-filter {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}

.chart-filter .el-select {
  width: 120px;
}
</style>